/**
 * MIT License
 * 
 * Copyright (c) 2024 - present @ ebraid
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */


#include <config.h>
#include <types.h>
#include <kernel/initcall.h>
#include <kernel/syslog.h>
#include <drivers/gpio.h>
#include <stm32f1.h>
#include <irqnum.h>
#include <drivers/irq.h>


#define EBTI_TO_CMSISTI(x)       ((x) - 16)


extern void Reset_Handler(void);
extern void xPortPendSVHandler(void);
extern void vPortSVCHandler( void );
extern void xPortSysTickHandler(void);


#define STACK_END_ADDR   0x20005000


static irq_handler_t eb_irq_table[CONFIG_IRQTABLE_SIZE] place_section(".eb_irq_table") = {0};


static int irq_init(void)
{
    eb_irq_table[0] = (irq_handler_t)STACK_END_ADDR;
    eb_irq_table[1] = (irq_handler_t)Reset_Handler;
    eb_irq_table[SVC_IRQNUM] = (irq_handler_t)vPortSVCHandler;
    eb_irq_table[PENDSV_IRQNUM] = (irq_handler_t)xPortPendSVHandler;
    eb_irq_table[SYSTICK_IRQNUM] = (irq_handler_t)xPortSysTickHandler;

    SCB->VTOR = (uint32_t)eb_irq_table;
    return 0;
}


int irq_request(uint32_t irq, irq_handler_t handler, void *data)
{
    if(eb_irq_table[irq] == NULL) {
        eb_irq_table[irq] =  handler;
        return 0;
    }
    else {
        return -1;
    }
}


void irq_free(uint32_t irq)
{
    eb_irq_table[irq] = NULL;
}


void irq_enable(uint32_t irq)
{
    NVIC_EnableIRQ(EBTI_TO_CMSISTI(irq));
}


void irq_disable(uint32_t irq)
{
    NVIC_DisableIRQ(EBTI_TO_CMSISTI(irq));
}


void irq_clear_flag(unsigned long arg)
{
    EXTI->PR |= (1 << IO_TO_PIN((uint32_t)(arg)));
}


core_initcall(irq_init);
